package cn.com.headfree.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gta.edu.sdk.base.controller.BaseController;
import com.gta.edu.sdk.common.dto.LoginUserInfo;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.common.dto.ResultData;
import com.gta.edu.sdk.common.dto.Sort;
import com.gta.edu.sdk.util.CommUtil;
import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.call.IDictionaryServiceCall;
import cn.com.headfree.entity.TCommonTask;
import cn.com.headfree.entity.TCommonTaskExecuteRecord;
import cn.com.headfree.service.IScheduleService;
import cn.com.headfree.service.ITaskService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@CrossOrigin("*")
@RestController
@RequestMapping(value = "/task", produces = "application/json;charset=UTF-8")
public class TaskController extends BaseController {
	private static final Logger log = LogManager.getLogger(TaskController.class);
	private static final String SYS_CODE = "common";
	private static final String SYS_CODE_VALUE = "sys_code";
	private static final String SYS_CODE_TASK = "task";
	private static final String SYS_CODE_TASK_STATUS_VALUE = "task_status";
	private static final String TASK_EXECUTE_RESULT = "task_execute_result";
	@Autowired
	private ITaskService taskService;
	@Autowired
	private IScheduleService scheduleService;
	@Autowired
	private IDictionaryServiceCall dictionaryServiceCall;

	/**
	 * @description 根据ID获取任务信息
	 * @author fengya
	 * @date 2020年7月15日 上午10:45:03
	 * @param id
	 * @return
	 * ResultData
	 */
	@RequestMapping("/getTask/{id}")
	public ResultData getTask(@PathVariable("id") String id) {
		ResultData result = new ResultData();
		if (!StringUtil.isNullOrEmpty(id)) {
			TCommonTask task = this.taskService.get(TCommonTask.class, id.trim());
			if (task != null) {
				result.setData(task);
			}
		}
		return result;
	}
	
	@RequestMapping("/recordList")
	public JSONObject recordList(Page<TCommonTaskExecuteRecord> page, TCommonTaskExecuteRecord record, Sort sort,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date startDate,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date endDate) {
		try {
			this.taskService.find(page, sort, record, startDate, endDate);
			List<TCommonTaskExecuteRecord> list = page.getResult();
			if (list != null && list.size() > 0) {
				ResultData recordResultResult = this.dictionaryServiceCall.findDictionaryByParentValue(SYS_CODE, TASK_EXECUTE_RESULT);
				if (!recordResultResult.isSuccess()) {
					throw new Exception(recordResultResult.getErrorMsg());
				}
				JSONArray recordResultArr = JSONArray.fromObject(recordResultResult.getData());
				Map<String, String> recordResultMap = this.paseDictData(recordResultArr);
				TCommonTaskExecuteRecord temp = null;
				for (int i = 0; i < list.size(); i++) {
					temp = list.get(i);
					temp.setExecuteResultName(recordResultMap.get(String.valueOf(temp.getExecuteResult())));
				}
			}
		} catch (Exception e) {
			log.error("获取定时任务列表失败！", e);
		}
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @description 根据任务ID和任务状态进行更改任务的状态信息，并控制任务
	 * @author fengya
	 * @date 2020年7月15日 上午10:45:20
	 * @param id
	 * @param status
	 * @return
	 * ResultData
	 */
	@RequestMapping("/changeTaskStatus/{id}/{status}")
	public ResultData changeTaskStatus(@PathVariable("id") String id, @PathVariable("status") int status) {
		ResultData result = new ResultData();
		try {
			if (!StringUtil.isNullOrEmpty(id)) {
				TCommonTask task = this.taskService.get(TCommonTask.class, id.trim());
				if (task != null) {
					if (status == 1) {
						task.setStatus(0);
						this.scheduleService.stopTask(task);
					} else {
						task.setStatus(1);
						this.scheduleService.startTask(task);
					}
					this.taskService.update(task);
					result.setData(task);
				}
			}
		} catch (Exception e) {
			String errorMsg = "改变流程状态出现了异常!";
			log.error(errorMsg, e);
			result.setSuccess(false);
			result.setErrorMsg(errorMsg);
		}
		return result;
	}

	/**
	 * @description 根据选择的任务ID进行删除任务
	 * @author fengya
	 * @date 2020年7月15日 上午10:45:58
	 * @param deleteIds
	 * @return
	 * ResultData
	 */
	@RequestMapping("/deleteTask")
	public ResultData deleteTask(String deleteIds) {
		ResultData result = new ResultData();
		if (!StringUtil.isNullOrEmpty(deleteIds)) {
			StringBuilder sb = new StringBuilder();
			String[] ids = deleteIds.split(",");
			String id = null;
			for (int i = 0; i < ids.length; i++) {
				id = ids[i];
				if (i == ids.length - 1) {
					sb.append("'").append(id).append("'");
				} else {
					sb.append("'").append(id).append("',");
				}
			}
			this.taskService.deleteTask(sb.toString());
		}
		return result;
	}

	/**
	 * @description 分页查询任务记录
	 * @author fengya
	 * @date 2020年7月15日 上午10:46:18
	 * @param page
	 * @param task
	 * @param sort
	 * @return
	 * JSONObject
	 */
	@RequestMapping("/list")
	public JSONObject list(Page<TCommonTask> page, TCommonTask task, Sort sort) {
		try {
			this.taskService.find(page, sort, task);
			List<TCommonTask> list = page.getResult();
			if (list != null && list.size() > 0) {
				ResultData sysCodeResult = this.dictionaryServiceCall.findDictionaryByParentValue(SYS_CODE, SYS_CODE_VALUE);
				ResultData taskStatusResult = this.dictionaryServiceCall.findDictionaryByParentValue(SYS_CODE_TASK, SYS_CODE_TASK_STATUS_VALUE);
				if (!sysCodeResult.isSuccess()) {
					throw new Exception(sysCodeResult.getErrorMsg());
				}
				if (!taskStatusResult.isSuccess()) {
					throw new Exception(taskStatusResult.getErrorMsg());
				}
				JSONArray sysCodeArr = JSONArray.fromObject(sysCodeResult.getData());
				JSONArray taskStatusArr = JSONArray.fromObject(taskStatusResult.getData());
				Map<String, String> sysCodeMap = this.paseDictData(sysCodeArr);
				Map<String, String> taskStatusMap = this.paseDictData(taskStatusArr);
				TCommonTask temp = null;
				for (int i = 0; i < list.size(); i++) {
					temp = list.get(i);
					temp.setSysCodeName(sysCodeMap.get(temp.getSysCode()));
					temp.setStatusName(taskStatusMap.get(String.valueOf(temp.getStatus())));
				}
			}
		} catch (Exception e) {
			log.error("获取定时任务列表失败！", e);
		}
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @description 根据数据字典集合构造出值和名的map集合
	 * @author fengya
	 * @date 2020年7月15日 上午10:46:42
	 * @param arr
	 * @return
	 * Map<String,String>
	 */
	private Map<String, String> paseDictData(JSONArray arr) {
		Map<String, String> data = new HashMap<String, String>(arr.size());
		JSONObject obj = null;
		for (int i = 0; i < arr.size(); i++) {
			obj = arr.getJSONObject(i);
			data.put(obj.getString("value"), obj.getString("name"));
		}
		return data;
	}

	/**
	 * @description 保存任务信息
	 * @author fengya
	 * @date 2020年7月15日 上午10:47:46
	 * @param task
	 * @return
	 * ResultData
	 */
	@RequestMapping("/save")
	public ResultData save(TCommonTask task) {
		LoginUserInfo userInfo = this.getLongUserInfo();
		ResultData result = new ResultData();
		try {
			if (task != null) {
				task.setUpdaterId(userInfo.getIscUserId());
				task.setUpdaterName(userInfo.getIscAdCode());
				task.setUpdateTime(new Date());
				if (StringUtil.isNullOrEmpty(task.getId())) {
					task.setId(null);
					task.setCreaterId(userInfo.getIscUserId());
					task.setCreaterName(userInfo.getIscAdCode());
					task.setCreateTime(new Date());
					this.taskService.save(task);
				} else {
					TCommonTask temp = this.taskService.get(TCommonTask.class, task.getId());
					task.setCreaterId(temp.getCreaterId());
					task.setCreaterName(temp.getCreaterName());
					task.setCreateTime(temp.getCreateTime());
					this.taskService.update(task);
				}
			}
		} catch (Exception e) {
			log.error("保存定时任务出现了异常！", e);
		}
		return result;
	}
}
